package com.huang.leetcode.stack;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @Author：CreateSequence
 * @Date：2020-07-28 12:08
 * @Description：有效的括号
 */
public class PB20 {

    public static void main(String[] args) {
        String s = "((";
        System.out.println(isValid(s));
    }

    public static boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<>();
        map.put('(', ')');
        map.put('{', '}');
        map.put('[', ']');

        if (s.length() > 0 && !map.containsKey(s.charAt(0)) || s.length() % 2 != 0) {
            return false;
        }

        Stack<Character> stack = new Stack<>();
        for (Character ch : s.toCharArray() ) {
            //如果是左括号就入栈
            if (map.containsKey(ch)) {
                stack.push(ch);
            } else if (!map.get(stack.pop()).equals(ch)) {
                //如果是右括号就弹出栈顶元素判断是否是对应左括号
                return false;
            }
        }
        return stack.empty();
    }

}
